<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Session;
use App\Services\TagService;

class TagController extends Controller{
	public function list(Request $request){
		$username = Session::get('username');
		if(!$username){
			return redirect('/admin/login');
		}else{
			$data['page_size_list'] = array(20,25,50,100);
			$data['page_size'] = $request->input('page_size') ? intval($request->input('page_size')) : 15;
			$data['keywords'] = $request->input('keywords') ? addslashes($request->input('keywords')) : '';
			$data['username'] = $username;

			$tag = new TagService;
			$data['taglist'] = $tag->getTagList($data['page_size'],$data['keywords']);

			return view('admin.tag.list',$data);
		}
	}

	public function create(){
		$username = Session::get('username');
		if(!$username){
			return redirect('/admin/login');
		}else{
			$data['username'] = $username;
			return view('admin.tag.add',$data);
		}
	}

	public function store(){
		$tag = new TagService;

		$data['tid'] = intval($_POST['tid']);
		$data['tag_name'] = addslashes($_POST['name']);
		$data['add_date'] = date('Y-m-d H:i:s');
		$data['isshow'] = 1;

		$taginfo = $tag->getTagInfoByName($data['tag_name']);

		if(!empty($taginfo)){
			$_data = array('code'=>300);
		}else{
			$res = $tag->insertTag($data);
			if($res){
				$_data = array('code'=>200);
			}else{
				$_data = array('code'=>400);
			}
		}

		return response()->json($_data);
	}

	public function edit($id){
		$username = Session::get('username');
		if(!$username){
			return redirect('/admin/login');
		}else{
			$tag = new TagService;

			$data['username'] = $username;
			$data['taginfo'] = $tag->getTagInfoById($id);

			return view('admin.tag.edit',$data);
		}

	}

	public function update(){
		$tag = new TagService;

		$id = intval($_POST['id']);

		$data['tag_name'] = addslashes($_POST['name']);
		$data['tid'] = intval($_POST['tid']);
		$data['update_date'] = date('Y-m-d H:i:s');

		$res = $tag->modifyTag($id,$data);
		if($res){
			$_data = array('code'=>200);
		}else{
			$_data = array('code'=>400);
		}

		return response()->json($_data);
	}

	public function del($id){
		$tag = new TagService;

		$data['isshow'] = 0;
		$data['update_date'] = date('Y-m-d H:i:s');

		$res = $tag->modifyTag($id,$data);
		if($res){
			$_data = array('code'=>200);
		}else{
			$_data = array('code'=>400);
		}

		return response()->json($_data);
	}
}